package com.chenkaiwei.shirojwtintegrationdemo;

import com.chenkaiwei.shirojwtintegrationdemo.entity.JwtUser;
import com.chenkaiwei.shirojwtintegrationdemo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BearerHttpAuthenticationFilter;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class DemoController {

    /**
     * 登陆
     */
    @PostMapping("/login")
    public Map login(@RequestBody User userInput) throws Exception {

        log.info(userInput.toString());
        String username = userInput.getUsername();
        String password = userInput.getPassword();

        Assert.notNull(username, "username不能为空");
        Assert.notNull(password, "password不能为空");

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);//realms会根据UsernamePasswordToken这个类型选用合适的realm来处理登陆

        //生成token
        Map<String,String> res=new HashMap<>();
        JwtUser jwtUser = (JwtUser) SecurityUtils.getSubject().getPrincipal();

        res.put("token",JwtUtil.createJwtTokenByUser(jwtUser));
        res.put("result","login success or other result message");
        return res;
    }


    @GetMapping("/whoami")
    public Map whoami(){
        JwtUser jwtUser = (JwtUser) SecurityUtils.getSubject().getPrincipal();

        Map<String,String> res=new HashMap<>();
        res.put("result","you are "+jwtUser);
        res.put("token",JwtUtil.createJwtTokenByUser(jwtUser));
        return res;
    }
//
    @GetMapping("/permissionDemo")
    @RequiresPermissions("pd")
    public Map permissionDemo(){

        Map<String,String> res=new HashMap<>();
        res.put("result","you have got the permission [pd]");

        JwtUser jwtUser = (JwtUser) SecurityUtils.getSubject().getPrincipal();
        res.put("token",JwtUtil.createJwtTokenByUser(jwtUser));

        return res;
    }

}
